﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SchEdu.Framework.DataModel;
using SchEdu.Framework.Exceptions;
using SchEdu.Framework.Logging;

namespace SchEdu.Framework.Constraint
{
    public class Constrainter
    {
        private Logger logger = new Logger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.ToString());

        protected Logger Logger
        {
            get { return logger; }
            set { logger = value; }
        }

        SchEduData schEduData;

        public SchEduData SchEduData
        {
            get { return schEduData; }
            set { schEduData = value; }
        }

        SchEduDataSet.SolutionRow solution;

        public SchEduDataSet.SolutionRow Solution
        {
            get { return solution; }
            set { solution = value; }
        }

        ConstraintList constraints = new ConstraintList();
        public ConstraintList Constraints
        {
            set
            {
                constraints = value;
            }
            get
            {
                return constraints;
            }
        }
        public Constrainter(SchEduData schEduData, SchEduDataSet.SolutionRow solution)
        {
            this.schEduData = schEduData;
            this.solution = solution;
        }

        public void Generate()
        {

            schEduData.RefreshAdditionalFields();

            Logger.Debug(string.Format("Generating Constraint for Solution {0}", solution.ID));

            schEduData.RefreshAdditionalFields();

            foreach (SchEduDataSet.AllocationRow allocation in solution.GetAllocationRows())
            {
                SchEduDataSet.OrderRow order = allocation.OrderRow;
                if (order == null)
                {
                    continue;
                }

                if (order.StartDate >= allocation.StartDate)
                {
                    order.StartDate = allocation.StartDate;
                }
                if (order.EndDate <= allocation.EndDate)
                {
                    order.EndDate = allocation.EndDate;
                }

            }

            foreach (IConstraint constraint in constraints)
            {
                foreach (SchEduDataSet.AllocationRow allocation in solution.GetAllocationRows())
                {
                    try
                    {
                        constraint.SchEduData = schEduData;
                        constraint.Allocation = allocation;
                        constraint.Run();
                    }
                    catch (ValidatorException ex)
                    {
                    }
                }
            }
        }
    }
}
